﻿// Developer Express Code Central Example:
// World Wide CRM Demo
// 
// The World Wide CRM demo is a next generation application with outstanding
// navigation capabilities and shows a reimagined view of customer contact and
// management. This demo showcases many of the most popular features of the
// WinForms Subscription.
// 
// You can find sample updates and versions for different programming languages here:
// http://www.devexpress.com/example=E3993

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;

namespace DevExpress.CrmDemo.Win.Controls {
    public partial class TextEditWithAutoSelect : ButtonEdit // this is ButtonEdit instead of TextEdit to allow for automatic ellipsis in the display
    {
        public TextEditWithAutoSelect() {
            Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            Properties.Appearance.TextOptions.Trimming = DevExpress.Utils.Trimming.EllipsisCharacter;
            Properties.Appearance.Options.UseTextOptions = true;
        }

        private bool _focused;

        protected override void OnEnter(EventArgs e) {
            base.OnEnter(e);

            // Allow regular editing
            Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.Standard;
            
            if (MouseButtons == MouseButtons.None) {
                SelectAll();
                MaskBoxFocus();
                _focused = true;
            }
        }
        void MaskBoxFocus() {
            if(this.Controls.Count > 0)
                this.Controls[0].Focus();
        }
        protected override void OnLeave(EventArgs e) {
            base.OnLeave(e);

            // Show ellipsis when complete text can't be shown.  From: http://www.devexpress.com/Support/Center/KB/p/A2124.aspx
            Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;

            _focused = false;
        }

        protected override void OnMouseUp(MouseEventArgs mevent) {
            base.OnMouseUp(mevent);
            if (!_focused) {
                if (SelectionLength == 0)
                    SelectAll();
                _focused = true;
            }
        }

        protected override void OnValidating(CancelEventArgs e) {
            if (this.Properties.Mask.MaskType == DevExpress.XtraEditors.Mask.MaskType.Numeric &&
                (string.IsNullOrEmpty(this.Text) || this.Text == "0" || this.Text == "$0" || this.Text == "0 %")) {
                this.Text = null;
            }

            base.OnValidating(e);
        }
    }
}
